<script setup lang='ts'>
import { onMounted, ref } from 'vue'
import { NButton, NCard, NForm, NFormItemRow, NInput, NInputGroup, NModal, NTabPane, NTabs, useMessage } from 'naive-ui'
import SubscribeTo from '../SubscribeTo/index.vue'
import { useUserStore } from '@/store'

import { fetchLogin, fetchRegister, fetchRegisterCode } from '@/api'
const message = useMessage()
const userStore = useUserStore()
const showModal = ref(false)
const subPay = ref<any>(null)
const show = () => {
  showModal.value = true
}
const bodyStyle = {
  width: '400px',
}

onMounted(() => {
  // const token = sessionStorage.getItem('token')
  // if (token)
  //   userStore.getUserInfo()
})
// 登录
const formRef = ref<any>(null)
const isLogin = ref(false)
const formValue = ref({
  phone: '',
  password: '',
})
const handleValidateClick = (e: MouseEvent) => {
  // console.log(e, formRef)
  e.preventDefault()
  formRef.value?.validate((errors: any) => {
    // console.log(6)
    if (!errors) {
      isLogin.value = true
      fetchLogin(formValue.value).then((res) => {
        // console.log(res)
        userStore.updateUserInfo({ name: res.data.name, token: res.data.token })
        message.success('登录成功')
        sessionStorage.setItem('token', res.data.token)
        formValue.value.phone = ''
        formValue.value.password = ''
        isLogin.value = false
        userStore.getUserInfo()
        showModal.value = false
      }).catch((error) => {
        isLogin.value = false
        // message.error('登录失败')
        message.error(error.message)
      })
    }
    else {
      console.log(errors)
    }
  })
}

const validatePass = (rule: any, value: any, callback: any) => {
  const regex = new RegExp('^(?![a-zA-Z]+$)(?![A-Z0-9]+$)(?![A-Z\W_!@#$%^&*`~()-+=]+$)(?![a-z0-9]+$)(?![a-z\W_!@#$%^&*`~()-+=]+$)(?![0-9\W_!@#$%^&*`~()-+=]+$)[a-zA-Z0-9\W_!@#$%^&*`~()-+=]{8,16}$')
  if (!regex.test(value)) {
    callback('密码长度8-16位且至少包含大写字母、小写字母、数字或特殊符号中的任意三种')
    return
  }
  callback()
}
const rules = {
  phone: [
    {
      required: true,
      message: '请输入手机号',
      trigger: ['input'],
      key: 'a',
    },
    {
      min: 11,
      max: 11,
      message: '请输入正确的手机号',
      trigger: ['input'],
    },
  ],
  password: [{
    required: true,
    message: '请输入密码',
    trigger: ['input'],
  }, {
    min: 8,
    max: 20,
    message: '密码长度最低为8位',
    trigger: ['input'],
  }, { validator: validatePass, trigger: 'input' }],
  code: [{
    required: true,
    message: '请输入验证码',
    trigger: ['input'],
  },
  {
    min: 6,
    max: 6,
    message: '验证码长度最低为6位',
    trigger: ['input'],
  },
  ],
}

// 注册
const formRefRs = ref<any>(null)
const isRegister = ref(false)
const textMsg = ref('发送验证码')
let num = 60
const isDisabled = ref(false)
const timers = ref()
const formValueRs = ref({
  phone: '',
  password: '',
  code: '',
})
const sendMsg = () => {
  formRefRs.value?.validate(
    (errors: any) => {
      if (errors) {
        console.error(errors)
      }
      else {
        isDisabled.value = true
        fetchRegisterCode({
          phone: formValueRs.value.phone,
        }).then((res) => {
          console.log(res)
          isDisabled.value = true
          timers.value = setInterval(() => {
            textMsg.value = `${num}秒后可发送`
            num = num - 1
            if (num === 0) {
              textMsg.value = '发送验证码'
              num = 60
              isDisabled.value = false
              clearInterval(timers.value)
            }
          }, 1000)
        }).catch((error) => {
          console.log(error)
          isDisabled.value = false
          message.error(error.message)
        })
      }
    },
    (rule: any) => {
      return rule?.key === 'a'
    },
  )
}
const handleValidateClickRs = (e: MouseEvent) => {
  e.preventDefault()
  formRefRs.value?.validate((errors: any) => {
    if (!errors) {
      isRegister.value = true
      fetchRegister({
        ...formValueRs.value,
        verifyPassword: formValueRs.value.password,
      }).then((res) => {
        message.success('注册成功，请登录')
        formValueRs.value.phone = ''
        formValueRs.value.code = ''
        formValueRs.value.password = ''
        isRegister.value = false
      }).catch((error) => {
        isRegister.value = false
        message.error(error.message)
        // message.error('注册失败')
      })
    }
    else {
      console.log(errors)
    }
  })
}
defineExpose({ show })
</script>

<template>
  <NModal v-model:show="showModal" class="custom-card" preset="card" title="" size="huge" :style="bodyStyle">
    <NCard title="MarkGpt" class="custom-card-put">
      <NTabs default-value="signin" size="large" justify-content="space-evenly">
        <NTabPane name="signin" tab="登录">
          <NForm ref="formRef" :label-width="80" :model="formValue" :rules="rules">
            <NFormItemRow label="手机号" path="phone">
              <NInput v-model:value="formValue.phone" type="number" placeholder="请输入手机号" />
            </NFormItemRow>
            <NFormItemRow label="密码" path="password">
              <NInput v-model:value="formValue.password" show-password-on="click" type="password" placeholder="密码" />
            </NFormItemRow>
          </NForm>
          <NButton type="primary" :loading="isLogin" block secondary strong @click="handleValidateClick">
            登录
          </NButton>
        </NTabPane>
        <NTabPane name="signup" tab="注册">
          <NForm ref="formRefRs" :label-width="80" :model="formValueRs" :rules="rules">
            <NFormItemRow label="手机号" path="phone">
              <NInput v-model:value="formValueRs.phone" type="number" placeholder="请输入手机号" />
            </NFormItemRow>
            <NFormItemRow label="验证码" path="code">
              <NInputGroup>
                <NInput v-model:value="formValueRs.code" />
                <NButton type="primary" ghost :disabled="isDisabled" @click="sendMsg">
                  {{ textMsg }}
                </NButton>
              </NInputGroup>
            </NFormItemRow>
            <NFormItemRow label="密码" path="password">
              <NInput v-model:value="formValueRs.password" show-password-on="click" type="password" placeholder="密码" />
            </NFormItemRow>
          </NForm>
          <NButton type="primary" :loading="isRegister" block secondary strong @click="handleValidateClickRs">
            注册
          </NButton>
        </NTabPane>
      </NTabs>
    </NCard>
  </NModal>
  <SubscribeTo ref="subPay" />
</template>

<style>
.custom-card .n-card-header {
  display: none !important;
}

.custom-card .n-card__content {
  padding: 0 !important;
}

.custom-card-put .n-card-header {
  display: block !important;
}

.custom-card-put .n-card__content {
  padding: 20px !important;
}
</style>
